/**
 * Created by zzy on 2017/9/22.
 */
import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    TextInput,
    View,
    PixelRatio,
    TouchableOpacity,
    Navigator,
    Image,
    Dimensions,
    FlatList,
    InteractionManager,
    Animated,
    Easing,
    DeviceEventEmitter,
    Button,
    Linking
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'
import NetRequestLuo from '../util/NetRequest'
import ClassifyTab from '../componentluo/classifytab'
import ConfirmOrder from '../../js/home/ConfirmOrder'
import ProductCellH from '../componentluo/ProductCellH'
import Contant from '../../js/Contant'
import ShareUtil from '../../js/common/ShareUtil'
import Share from '../../js/component/ShareModal'
import {observer} from 'mobx-react/native'
import {observable, action, computed} from 'mobx'
import shoppingCartStore from '../store/ShoppingCartStore'
import CommonUtil from '../util/CommonUtil'
import addressMgrStore from '../../js/store/AddrMgrStore'

let {width,height} = Dimensions.get('window');
const padding = 5;
const IconSize = 80;
@observer
export default class WaterStation extends Component{
    static navigationOptions = {
        header: null
    };
    @observable shopSelectCount=0;
    @observable sortType='desc';
    @observable categoryType='saleMount';
    @observable sortSelectIndex=0;
    @observable typeData=[{title:'推荐',sort:false},{title:'销量',sort:false},{title:'价格',sort:true,sortType:true}];
    constructor(props){
        super(props);
        this.state={
            loading:true,
            productlist:[],
            shop:{},
         };
        this.shopId=this.props.navigation.state.params.shopId;
    }
    render(){
        return <View style={{flex:1,backgroundColor:'white'}}>
                <Head {...this.props} share={this._startShare.bind(this)}/>
                <FlatList
                    style={{backgroundColor:'white'}}
                    ListHeaderComponent={this._header()}
                    onRefresh={this._onRefresh.bind(this)}
                    refreshing={this.state.loading}
                    onEndReachedThreshold={0.1}
                    onEndReached={this._onEndReached.bind(this)}
                    data={this.state.productlist}
                    numColumns={2}
                    keyExtractor={(item,index) => index}
                    renderItem={({item}) => <ProductCellH item={item} addToShoppingCart={this._addToShoppingCart.bind(this)} callback={()=>{
                        this.props.navigation.navigate('ProductsDetailsLuo',{productItemId:item.productItemModels[0].productItemId,shopId:this.shopId});
                    }}/>}
                />
                <Footer ref="footer" telephoneNumber={Contant.SERVICEPHONE} addshoppingCart={()=>{
                    if(this.shopSelectCount==0)return;
                    this.props.navigation.navigate('ConfirmOrder',{shopId:this.shopId})
                }}
                  shoppingCart={()=>{this.props.navigation.navigate('ShoppingCart')}}
                  shopSelectCount={this.shopSelectCount}
                />
            <Share ref="modal1" shareCall={this._share} info={this.state.shop}/>
        </View>
    }
    componentDidMount(){
      this._shopInfo();
      this._getProductList();
      this.getShopCart();
    }
    getShopCart(){
        let param={
            shopId: this.shopId,
        };
        NetRequestLuo.getShopSelectedProductList(param).then((data)=>{
            LOG('店铺购物车---------'+JSON.stringify(data));
            this.shopSelectCount=data.selectCount;
        })
    }
    _startShare(){
        this.refs.modal1._open();
    };
    _share(type, shop) {
        var shareParam = {
            type: 'news',
            title: '汇贝送水',
            description: shop.name ,
            messageAction: undefined,
            messageExt: undefined,
            webpageUrl: shop.shareUrl,
        };
        type == 0 ? ShareUtil.shareToSession(shareParam) : ShareUtil.shareToTimeline(shareParam)
    }
    _shopInfo(){
        let shopParam={
            cityName: '',
            latitude: addressMgrStore.activeAddress.latitude,
            longtitude: addressMgrStore.activeAddress.longitude,
            shopId: this.shopId
        };
        NetRequestLuo.shopInfo(shopParam).then((data)=>{
            LOG('店铺信息---------'+JSON.stringify(data));
            this.setState({
                shop:data
            })
        })
    }
    _header(){
        return ()=><Header info={this.state.shop} typeData={this.typeData} {...this.props} collect={this._collect.bind(this)} sort={this._getProductList.bind(this)} sortSelectIndex={this.sortSelectIndex}/>
    }
    _collect(id,type){
        let collectParam={
            shopId:id,
            type:type
        };
        NetRequestLuo.collect(collectParam).then((data)=>{
            LOG('收藏---------'+JSON.stringify(data));
            this._shopInfo();
        })
    }
    _getProductList(index=0){
        this.sortSelectIndex=index;
        switch (index){
            case 0:
                this.sortType='desc';
                this.categoryType='saleMount';
                break;
            case 1:
                this.sortType='desc';
                this.categoryType='saleMount';
                break;
            case 2:
                this.typeData[index].sortType==true?this.sortType='desc':this.sortType='asc';
                this.categoryType='price';
                this.typeData[index].sortType=!this.typeData[index].sortType;
                break;
        }
        let param={
            shopId:this.shopId,
            sortType:this.sortType,
            categoryType:this.categoryType
        };
        InteractionManager.runAfterInteractions(()=>{
            NetRequestLuo.oldproductList(param,'entityProduct').then((data)=>{
            LOG('商品列表----------'+JSON.stringify(data));
            this.setState({
                loading:false,
                productlist:data.productList
            })
        })
        });
    }
    _onRefresh(){
        this._getProductList();
    }
    _onEndReached(){

    }
    _addToShoppingCart(item){
        this.refs.footer.animateShoppingCart();
        let param={
            productItemId: item.productItemModels[0].productItemId,
            productType: item.type,
            shopId: this.shopId,
        };
        NetRequestLuo.addShoppingCart(param,'increase').then((data)=>{
              LOG('加入购物车--------'+JSON.stringify(data));
            shoppingCartStore.getShoppingCart();
            DeviceEventEmitter.emit('refreshShopList');//刷新购物车
            this.getShopCart();//刷新店铺购物车
        });

    }
}
class Head extends Component{
    render(){
        let {goBack} = this.props.navigation;
        let {share}=this.props;
        return <View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center',height:50,backgroundColor:'white'}}>

            <TouchableOpacity activeOpacity={1}
                              onPress={()=>{
                                  goBack()
                              }}>
                <Icon name="ios-arrow-back" size={30} style={{padding:10}}/>
            </TouchableOpacity>
            <Text style={{color:'black',fontSize:18}}>店铺</Text>
            <TouchableOpacity activeOpacity={1}
                              onPress={()=>{
                                  share()
                              }}>
            <Image style={{width:25,height:25,marginRight:10}} source={require('../../asserts/shop/common_head_icon_share.png')}></Image>
            </TouchableOpacity>
        </View>
    }
}
class Header extends Component{
    render(){
        let {totalProductCount,shopId,name,address,distance,saleMount,imageUrl,collectFlg,fansCount,score} = this.props.info;
        let {collect,sort,sortSelectIndex} = this.props;
        return <TouchableOpacity
            activeOpacity={1}
            onPress={()=>{

            }}>
            <View style={{height:80,backgroundColor:'#fff',flexDirection:'row'}}>
                <Image style={{position:'absolute',left:padding,top:padding,bottom:padding,width:IconSize-2*padding}} source={{uri:imageUrl}}/>
                <View style={{justifyContent:'space-around',marginLeft:IconSize+padding}}>
                    <Text>{name}</Text>
                    <View style={{flexDirection:'row'}}>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <View style={{flexDirection:'row'}}>
                            </View>
                            <View style={{flexDirection:'row',alignItems:'center'}}>
                                {CommonUtil.getStoreStars(score)}
                                <Text style={[styles.grayText,{marginLeft:10}]}>月售{saleMount}</Text>
                            </View>
                        </View>
                    </View>
                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <Image style={{width:12,height:16,marginRight:3,resizeMode:'contain'}} source={require('../../asserts/common/station_details_icon_location.png')}/>
                            <Text style={[styles.grayText,{maxWidth:180}]} numberOfLines={1}>{address}</Text>
                        </View>
                        <Text style={[styles.grayText,{marginLeft:20}]}>{distance}</Text>
                    </View>
                </View>
                <View style={{justifyContent:'center',position:'absolute',right:10,height:IconSize}}>
                    <Icon name="ios-arrow-forward" size={30}/>
                </View>
            </View>
            <View style={{flexDirection:'row',backgroundColor:'white',marginTop:2,padding:5}}>
                <View style={[styles.center,{flex:1}]}>
                    <Text>{totalProductCount}</Text>
                    <Text>全部商品</Text>
                </View>
                <View style={[styles.center,{flex:1}]}>
                    <Text>{fansCount}</Text>
                    <Text>粉丝</Text>
                </View>
                <TouchableOpacity style={[styles.center,{flex:1}]} onPress={()=>{collect(shopId,'shop')}}>
                    {
                        collectFlg==true?<Image style={{width:15,height:15,resizeMode:'contain'}} source={require('../../luoasserts/shop/bottom_btn_collection_s.png')}></Image>
                            :<Image style={{width:15,height:15,resizeMode:'contain'}} source={require('../../luoasserts/shop/bottom_btn_collection_n.png')}></Image>
                    }
                    <Text>收藏</Text>
                </TouchableOpacity>
            </View>
            <ClassifyTab data={this.props.typeData} sortSelectIndex={sortSelectIndex} {...this.props} handler={(index)=>{
                sort(index);
            }}/>
        </TouchableOpacity>

    };
}
@observer
class Footer extends Component{

    constructor(props){
        super(props);
        this.state = {
            bounceValue:new Animated.Value(1),
        }
    }
    animateShoppingCart(){
        this.state.bounceValue.setValue(1.8) ;   // 设置一个较大的初始值
        Animated.spring(                          // 可选的基本动画类型: spring, decay, timing
            this.state.bounceValue,                 // 将`bounceValue`值动画化
            {
                toValue: 1,                         // 将其值以动画的形式改到一个较小值
                friction: 1,                          // Bouncier spring
            }
        ).start() ;                             // 开始执行动画
    }
    render(){
        let {addshoppingCart,shoppingCart,shopSelectCount} = this.props;
        let payBtColor=shopSelectCount==0?'gray':'red';
        return <View style={{height:44,backgroundColor:'white',flexDirection:'row',justifyContent:'center',alignItems:'center'}}>
            <TouchableOpacity activeOpacity={0.9} style={[styles.footerItem,styles.center]} onPress={()=>{
                Linking.openURL('tel:'+this.props.telephoneNumber)
            }}>
                <Icon name="ios-call" size={24}/>
                <Text style={styles.footerText}>客服</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.footerItem,styles.center]}  onPress={shoppingCart}>
                <Icon name="ios-cart-outline" size={24} />
                <Text style={styles.footerText}>购物车</Text>
                {
                    shopSelectCount==0?(null):<Animated.View
                        style={{transform:[                        // `transform`是一个有序数组（动画按顺序执行）
                            {scale: this.state.bounceValue}],height:17,borderRadius:11,backgroundColor:'red',position:'absolute',right:35,top:0,justifyContent:'center',alignItems:'center'}}>
                        <Text style={{color:'#fff',fontSize:this.state.fontSize}}>{'  '+shopSelectCount+'  '}</Text>
                    </Animated.View>
                }
            </TouchableOpacity>
            <TouchableOpacity activeOpacity={0.9} style={[{flexGrow:1,height:44,backgroundColor:payBtColor},styles.center]} onPress={addshoppingCart}>
                <Text style={{color:'white',fontSize:15}}>去结算</Text>
            </TouchableOpacity>
        </View>
    }
}

const styles = {
    menuitem:{
        flexGrow:1,
        height:40,
        alignItems:'center',
        justifyContent:'center'
    },
    border:{
        borderRightColor:'#f5f5f5',
        borderRightWidth:1/PixelRatio.get()
    },
    footerItem:{
        height:40,
        flexGrow:1
    },
    footerText:{
        fontSize:12
    },
    center:{
        alignItems:'center',
        justifyContent:'center'
    },
    borderBottom:{
        borderBottomColor:'#f5f5f5',
        borderBottomWidth:1/PixelRatio.get()
    },
    grayText:{
        fontSize:12,
        color:'gray'
    },
    btn: {
        margin: 10,
        backgroundColor: "#3B5998",
        color: "white",
        padding: 10
    },
}